package com.dy.placeOrder.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;
@RequestMapping("/placeOrder")
@RestController
public class UploadController {
    @Value("${aliyun.endpoint}")
    private String endpoint;
    @Value("${aliyun.keyId}")
    private String keyid;
    @Value("${aliyun.keySecret}")
    private String keysecret;
    @Value("${aliyun.bucketName}")
    private String buncket;


    @PostMapping("/aaa")
    public String fileUpload(MultipartFile file) {
        System.out.println("上传文件");
        String url="";
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, keyid, keysecret);
        try {
            // 创建PutObjectRequest对象。
            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();

            String replace = UUID.randomUUID().toString().replace("-", "");
            originalFilename = replace+originalFilename;
            String time = new DateTime().toString("yyyy/MM/dd");
            originalFilename = time+"/"+originalFilename;

            PutObjectResult putObjectResult = ossClient.putObject(buncket, originalFilename, inputStream);

            url="https://"+buncket+"."+endpoint+"/"+originalFilename;
        } catch (Exception ce) {
            System.out.println("上传异常--");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return url;
    }

}
